package cn.windy.samary.module.admin.controller;

import cn.windy.samary.core.annotation.OpLog;
import cn.windy.samary.module.abstracts.controller.AbstractController;
import cn.windy.samary.module.admin.common.Tree;
import cn.windy.samary.module.admin.common.UserLine;
import cn.windy.samary.module.admin.common.UserVo;
import cn.windy.samary.module.admin.entity.Dept;
import cn.windy.samary.module.admin.entity.Role;
import cn.windy.samary.module.admin.entity.User;
import cn.windy.samary.module.admin.entity.UserRole;
import cn.windy.samary.module.admin.service.IDeptService;
import cn.windy.samary.module.admin.service.IRoleService;
import cn.windy.samary.module.admin.service.IUserRoleService;
import cn.windy.samary.module.admin.service.IUserService;
import cn.windy.samary.utils.PageContent;
import cn.windy.samary.utils.Res;
import cn.windy.samary.utils.ShiroUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyl
 * @date 2018/5/21 15:24
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends AbstractController {

    private String prefix = "admin/user/";

    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IUserRoleService userRoleService;
    @Resource
    private IDeptService deptService;

    @GetMapping
    @OpLog(value = "打开用户管理主页")
    @RequiresPermissions("admin:user:user")
    public String index(HttpServletRequest request, Model model) {
        model.addAttribute("basePath", getBasePath(request));
        return prefix + "user";
    }

    @ResponseBody
    @GetMapping(value = "/list")
    @OpLog(value = "查询用户列表")
    @RequiresPermissions("admin:user:user")
    public Res list(PageContent pageContent,
                    String username, String nickname, String deptId) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(username)) {
            criteria.andLike("username", "%" + username + "%");
        }
        if (StringUtils.isNotBlank(nickname)) {
            criteria.andLike("nickname", "%" + nickname + "%");
        }
        if (StringUtils.isNotBlank(deptId)) {
            criteria.andEqualTo("deptId", deptId);
        }
        UserLine userLine = ShiroUtils.getUserLine();
        if (!"0001".equals(userLine.getId())) {
            criteria.andNotEqualTo("id", "0001");
        }
        Page<User> page = PageHelper.offsetPage(pageContent.getOffset(), pageContent.getLimit());
        List<User> users = userService.selectByExample(example);
        for (User user : users) {
            String roleStrings = userService.getRoleShownameByUserId(user.getId());
            user.setRole(roleStrings);
        }

        return Res.rows(users, page.getTotal());
    }

    @OpLog("添加用户")
    @GetMapping("add")
    @RequiresPermissions("admin:user:add")
    public String add(HttpServletRequest request, Model model) {
        List<Role> roles = roleService.selectAll();
        UserLine userLine = ShiroUtils.getUserLine();
        if (!"0001".equals(userLine.getId())) {
            roles.removeIf(role -> "0001".equals(role.getId()));
        }
        model.addAttribute("roles", roles);
        return prefix + "userAdd";
    }

    @OpLog("编辑用户")
    @GetMapping("edit/{id}")
    @RequiresPermissions("admin:user:edit")
    public String edit(HttpServletRequest request, Model model,
                       @PathVariable String id) {
        //查询角色
        List<Role> roles = roleService.selectAll();
        UserLine userLine = ShiroUtils.getUserLine();
        if (!"0001".equals(userLine.getId())) {
            roles.removeIf(role -> "0001".equals(role.getId()));
        }
        //查询已有角色
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        List<UserRole> userRoles = userRoleService.select(userRole);
        List<Map<String, Object>> ro = new ArrayList<>();
        for (Role role : roles) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", role.getId());
            map.put("showname", role.getShowname());
            for (UserRole userRole1 : userRoles) {
                if (userRole1.getRoleId().equals(role.getId())) {
                    map.put("checked", true);
                    break;
                }
            }
            ro.add(map);
        }
        model.addAttribute("roles", ro);
        User user = userService.selectByPrimaryKey(id);
        if (StringUtils.isNotBlank(user.getDeptId())) {
            Dept dept = new Dept();
            dept.setId(user.getDeptId());
            Dept select = deptService.selectOne(dept);
            if (select != null) {
                user.setDeptName(select.getName());
            }
        }
        model.addAttribute("user", user);
        return prefix + "userEdit";
    }

    @ResponseBody
    @OpLog("保存用户")
    @PostMapping("save")
    @RequiresPermissions("admin:user:add")
    public Object save(@Valid User entity, String roles) {
        User user = new User();
        String username = entity.getUsername();
        user.setUsername(username);
        User user1 = userService.selectOne(user);
        if (user1 != null) {
            return Res.error(599, "该账号已存在！");
        }
        int i = userService.save(entity, roles);
        return i != 0 ? Res.ok() : Res.error();
    }

    @ResponseBody
    @OpLog("更新用户")
    @PutMapping("update")
    @RequiresPermissions("admin:user:edit")
    public Object update(@Valid User entity, String roles) {
        int i = userService.update(entity, roles);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("删除用户")
    @ResponseBody
    @DeleteMapping("remove")
    @RequiresPermissions("admin:user:remove")
    public Object remove(String id) {
        if ("0001".equals(id)) {
            return Res.ok("内置用户无法删除！");
        }
        int i = userService.deleteByPrimaryKey(id);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("批量删除用户")
    @ResponseBody
    @DeleteMapping("batchRemove")
    @RequiresPermissions("admin:user:batchRemove")
    public Object batchRemove(@RequestParam(value = "ids[]") String[] ids) {
        List<String> idsList = new ArrayList<>();
        for (String id : ids) {
            if (!"0001".equals(id)) {
                idsList.add(id);
            }
        }
        if (idsList.size() != 0) {
            userService.deleteByPrimaryKeys(idsList);
        }
        return Res.ok();
    }

    @OpLog("检查用户名是否存在")
    @GetMapping("/exist")
    @ResponseBody
    public boolean exist(String username) {
        User user = new User();
        user.setUsername(username);
        User select = userService.selectOne(user);
        return select == null;
    }

    @ResponseBody
    @PostMapping("/setRole")
    @OpLog(value = "设置用户角色")
    public Object setRole(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "userIds[]", required = true) String[] userIds,
                          @RequestParam(value = "roleIds[]", required = false) String[] roleIds) {
        userService.setRole(userIds, roleIds);
        return Res.ok();
    }

    @GetMapping("/personal")
    @OpLog("个人设置")
    String personal(Model model) {
        User user = userService.selectByPrimaryKey(getUserId());
        model.addAttribute("user", user);
        return prefix + "/personal";
    }

    @RequiresPermissions("admin:user:edit")
    @OpLog("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Res updatePeronal(User user) {
        if (userService.updatePersonal(user) > 0) {
            return Res.ok();
        }
        return Res.error();
    }

    @RequiresPermissions("admin:user:resetPwd")
    @OpLog("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") String userId, Model model) {
        User user = new User();
        user.setId(userId);
        model.addAttribute("user", user);
        return prefix + "/reset_pwd";
    }

    @OpLog("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    public Res resetPwd(UserVo userVo) {
        return userService.resetPwd(userVo);
    }

    @RequiresPermissions("admin:user:resetPwd")
    @OpLog("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    public Res adminResetPwd(User user) {
        if ("0001".equals(user.getId())) {
            return Res.error("系统内置用户密码不允许直接重置！");
        }
        int i = userService.adminResetPwd(user);
        return i != 0 ? Res.ok() : Res.error();
    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<Dept> tree() {
        return userService.getTree();
    }

    @GetMapping("/treeView")
    public String treeView() {
        return prefix + "/userTree";
    }
}
